package com.biz.primus.ms.depot.dao.specfication;

import com.biz.primus.base.enums.CommonStatus;
import com.biz.primus.model.depot.vo.QrCodeBackendPageReqVo;
import com.biz.primus.ms.depot.dao.po.QrCode;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * QrCodeSpecfication
 *
 * @author JKLiues
 * @date 2017年11月07日
 */
@AllArgsConstructor
public class QrCodeSpecfication implements Specification<QrCode> {

    private QrCodeBackendPageReqVo reqVo;

    @Override
    public Predicate toPredicate(Root<QrCode> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        List<Predicate> predicates = new ArrayList<>();
        if (StringUtils.isNotBlank(reqVo.getQrCode())) {
            predicates.add(cb.equal(root.get("qrCode").as(String.class), reqVo.getQrCode()));
        }
        if (StringUtils.isNotBlank(reqVo.getParam())) {
            predicates.add(cb.equal(root.get("param").as(String.class), reqVo.getParam()));
        }
        if (reqVo.getBeginTime() != null) {
            predicates.add(cb.greaterThanOrEqualTo(root.get("beginTime").as(Timestamp.class), reqVo.getBeginTime()));
        }
        if (reqVo.getEndTime() != null) {
            predicates.add(cb.greaterThanOrEqualTo(root.get("endTime").as(Timestamp.class), reqVo.getEndTime()));
        }
        predicates.add(cb.equal(root.get("status").as(CommonStatus.class), CommonStatus.ENABLE));
        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    }
}